<template>
<el-select v-model="actualValue"
      filterable
      remote
      reserve-keyword
      :placeholder="placeholder"
      :remote-method="remoteMethod"
      :loading="loading">
  <slot :options="options">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </slot>
</el-select>
</template>

<script lang="ts">

import { Vue, Component, Prop, Emit, Inject, Ref } from 'vue-property-decorator'

export interface SelectOption {
  label: string;
  value: any;
  [name: string]: any;
}

@Component
export default class SearchSelect extends Vue {
  @Prop() value!: any

  @Prop(Function) loader!: (keyword: string) => Promise<SelectOption[]>

  @Prop({ type: String, default: '请输入账号或名称' }) placeholder!: string

  @Emit() input (value: any) {}

  @Emit() select (item: any) {}

  loading = false

  options: any[] = []

  get actualValue () {
    return this.value
  }

  set actualValue (value: any) {
    this.input(value)
    const item = this.options.find(v => v.value === value)
    if (item) this.select(item)
  }

  remoteMethod (keyword: string) {
    this.loading = true
    this.loader(keyword).then(data => {
      this.options = data || []
    }).finally(() => {
      this.loading = false
    })
  }

  mounted () {
    this.remoteMethod('')
  }
}
</script>
